import { ReactElement, InputHTMLAttributes, ChangeEvent, forwardRef } from 'react'
import classNames from 'classnames'
import { IconProp } from '@fortawesome/fontawesome-svg-core'
import Icon from '../Icon'

type InputSize = 'lg' | 'sm' // 大小
export interface InputProps extends Omit<InputHTMLAttributes<HTMLElement>, 'size'> {
  disabled?: boolean
  size?: InputSize
  icon?: IconProp
  prepend?: string | ReactElement // 前缀
  append?: string | ReactElement // 后缀
  onChange?: (e: ChangeEvent<HTMLInputElement>) => void
}

export const Input = forwardRef<HTMLInputElement, InputProps>((props, ref) => {
  const { disabled, size, icon, prepend, append, style, ...restProps } = props
  // 类名
  const cnames = classNames('dog-input-wrapper', {
    [`input-size-${size}`]: size, // 大小
    'is-disabled': disabled, // 禁用
    'input-group': prepend || append, // 是否有前缀或后缀
    'input-group-append': !!append, // 是否有后缀
    'input-group-prepend': !!prepend // 是否有前缀
  })
  // 修复受控组件
  const fixControlledValue = (value: any) => {
    if (typeof value === 'undefined' || value === null) return ''
    return value
  }
  // 受控组件
  if ('value' in props) {
    delete restProps.defaultValue // 删除默认值
    restProps.value = fixControlledValue(props.value)
  }
  return (
    <div className={cnames} style={style}>
      {prepend && <div className="dog-input-group-prepend">{prepend}</div>}
      {icon && (
        <div className="icon-wrapper">
          <Icon icon={icon} title={`title-${icon}`} />
        </div>
      )}
      <input ref={ref} className="dog-input-inner" disabled={disabled} {...restProps} />
      {append && <div className="dog-input-group-append">{append}</div>}
    </div>
  )
})

export default Input
